// JavaScript Document
// client.js

var socket;
var inputlist = [];
var tmp;
var listcount = -1;
var grtcount  = -1; // The maximum count so nothing is lost

function init(){
  var host = "ws://localhost:12345";
  try{
    socket = new WebSocket(host);
    log("<div id='local_echo'>WebSocket - status "+socket.readyState+"</div>");
    socket.onopen    = function(msg){ log("<div id='local_echo'>Welcome - status "+this.readyState+"</div>"); };
    socket.onmessage = function(msg){ processJSON(msg.data); };
    socket.onclose   = function(msg){ log("<div id='local_echo'>Disconnected - status "+this.readyState+"</div>"); };
  }
  catch(ex){ log(ex); }
  $("msg").focus();
}

function send(){
  var txt,msg;
  txt = $("msg");
  msg = txt.value;
  if(!msg){ return; }
  txt.value="";
  txt.focus();
  storemsg(msg);
  // However one wishes to echo the data, one option below
  log("<div id='local_echo'>&raquo; " + msg + "</div>");
  
  if(client_state.loaded) {  cmd_handler(msg); } 
  else { try{ socket.send(msg); } catch(ex){ log(ex); } };
}

function processJSON(msg) {
	msg = msg.replace(String.fromCharCode(0),"");   // our server sends an 
	msg = msg.replace(String.fromCharCode(255),""); // extra bit or two every time?
	
	//debug(msg);
	data = JSON.parse(msg);
	
	// Sent once on startup
	if (data.loaded) { client_state = data; return; }
	
	// Most often, we just get data to send straight to a console
	if (data.general_msg) { log("<div id='general_msg'>" + data.general_msg + "</div>"); return; }
	
	// Sent on continuous updates based on changes in game state
	for(i in data) {
		client_state[i] = data[i];
		//alert(data[i]);
	}
	
	clientUpdate();
	
}

function debug(msg) {
	log("<br class=clear />");
	log(msg);
	log("<br class=clear />");
}


function quit(){
  log("Goodbye!");
  socket.close();
  socket=null;
}

// Utilities
function $(id){ return document.getElementById(id); }
function log(msg)
{ 
	$("log").innerHTML+=msg; 
	$("log").scrollTop = $("log").scrollHeight;	
}

function onkey(event){
	if(event.keyCode==13){ send(); } 
	if(event.keyCode==38){ retrieveup(); }
	if(event.keyCode==40){ retrievedown(); }
}

function storemsg($msg) {	
	grtcount++;
	listcount = grtcount;
	inputlist[grtcount] = $msg;
}

function retrieveup() {	
	if ((listcount == grtcount)) {  inputlist[listcount+1] = $("msg").value; }
	if (listcount > -1) { $("msg").value = inputlist[listcount]; }
	if (listcount > 0) { 
		listcount--;
	}
}
	
function retrievedown() {	
	listcount++;
	if (listcount <= grtcount) { 
		$("msg").value = inputlist[listcount];
	} else { 
		$("msg").value = inputlist[listcount];
		listcount--;
	}
}